<template>
  <div class="user-list">
    <!-- 搜索栏 -->
    <el-card class="search-card mb-4">
      <el-form :model="searchForm" inline>
        <el-form-item label="账号">
          <el-input v-model="searchForm.account" placeholder="请输入账号" clearable />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="searchForm.nickname" placeholder="请输入昵称" clearable />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.mobile" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="用户类型">
          <el-select v-model="searchForm.userType" placeholder="请选择用户类型" clearable>
            <el-option label="普通用户" :value="0" />
            <el-option label="VIP用户" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <div>
            <el-button type="primary" @click="handleAdd">添加用户</el-button>
            <el-button type="danger" :disabled="!selectedUsers.length" @click="handleBatchDelete"
              >批量删除</el-button
            >
          </div>
        </div>
      </template>

      <el-table
        :data="userList"
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="用户信息" min-width="200">
          <template #default="{ row }">
            <div style="display: flex; align-items: center">
              <el-avatar :src="row.avatar" :size="40" style="margin-right: 10px" />
              <div>
                <div>{{ row.account }}</div>
                <div style="color: #999; font-size: 12px">未设置昵称</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" width="120" />
        <el-table-column prop="userType" label="用户类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.userType === 0 ? 'info' : 'success'" size="small">
              {{ row.userType === 0 ? '普通用户' : 'VIP用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="birthday" label="生日" width="100" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-popconfirm title="确认删除该用户吗？" @confirm="handleDelete(row)">
              <template #reference>
                <el-button type="danger" link>删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <span>共 {{ total }} 条</span>
        <el-select v-model="pageSize" class="mx-2" @change="handleSizeChange">
          <el-option
            v-for="item in [15, 30, 50, 100]"
            :key="item"
            :label="`${item}条/页`"
            :value="item"
          />
        </el-select>
        <el-pagination
          v-model:current-page="currentPage"
          :total="total"
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="userForm"
        :rules="rules"
        label-width="100px"
        style="max-width: 460px"
      >
        <el-form-item label="账号" prop="account">
          <el-input v-model="userForm.account" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="userForm.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="userForm.birthday"
            type="date"
            placeholder="选择生日"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="用户类型" prop="userType">
          <el-select v-model="userForm.userType" placeholder="请选择用户类型" style="width: 100%">
            <el-option label="普通用户" :value="0" />
            <el-option label="VIP用户" :value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserListAPI } from '@/apis/admin'

// 搜索表单
const searchForm = ref({
  account: '',
  nickname: '',
  mobile: '',
  userType: ''
})

// 表格数据
const loading = ref(false)
const userList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const formRef = ref(null)
const userForm = ref({
  account: '',
  nickname: '',
  password: '',
  mobile: '',
  birthday: '',
  userType: 0,
  gender: '',
  avatar: '',
  cityCode: '',
  provinceCode: '',
  profession: ''
})

// 表单验证规则
const rules = {
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  userType: [{ required: true, message: '请选择用户类型', trigger: 'change' }]
}

// 获取用户列表
const getUserData = async () => {
  loading.value = true
  try {
    const res = await getUserListAPI()
    if (res.code === 0) {
      userList.value = res.data
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索和重置
const handleSearch = () => {
  currentPage.value = 1
  getUserData()
}

const resetSearch = () => {
  searchForm.value = {
    account: '',
    nickname: '',
    mobile: '',
    userType: ''
  }
  handleSearch()
}

// 添加/编辑用户
const handleAdd = () => {
  dialogType.value = 'add'
  userForm.value = {
    account: '',
    nickname: '',
    password: '',
    mobile: '',
    birthday: '',
    userType: 0,
    gender: '',
    avatar: '',
    cityCode: '',
    provinceCode: '',
    profession: ''
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  userForm.value = { ...row }
  dialogVisible.value = true
}

const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 这里调用添加或更新用户的API
        const message = dialogType.value === 'add' ? '用户添加成功' : '用户更新成功'
        ElMessage.success(message)
        dialogVisible.value = false
        getUserData()
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
  })
}

// 添加选中用户数组
const selectedUsers = ref([])

// 选择变化处理
const handleSelectionChange = (val) => {
  selectedUsers.value = val
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm('确认删除选中的用户吗？', '提示', {
      type: 'warning'
    })
    // 调用批量删除API
    // const ids = selectedUsers.value.map(item => item.id)
    // await deleteUsersBatch(ids)
    ElMessage.success('批量删除成功')
    getUserData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 修改删除用户方法,添加确认提示
const handleDelete = async () => {
  try {
    // 调用删除用户API
    // await deleteUser(row.id)
    ElMessage.success('删除成功')
    getUserData()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 添加分页事件处理方法
const handleSizeChange = (val) => {
  pageSize.value = val
  getUserData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getUserData()
}

onMounted(() => {
  getUserData()
})
</script>

<style lang="scss" scoped>
.el-header {
  background-color: #fff;
}
.el-container {
  height: 100vh;
  background-color: white;
}
.el-aside {
  height: 100vh;
  background-color: #fd715d;
  overflow-y: hidden;
}

/* 添加分页容器样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 12px;
}

/* 调整选择器宽度和样式 */
.pagination-container .el-select {
  width: 80px; /* 减小选择器宽度 */
}

/* 调整分页器样式 */
:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #fd715d;
}

/* 调整每页条数选择器的样式 */
:deep(.el-select-dropdown__item) {
  text-align: center;
  padding: 0 10px;
}
</style>
